import { Component,OnInit,ElementRef,Output,EventEmitter } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import lodash from 'lodash';

@Component({
    selector: 'app-model-menu',
    templateUrl: './model-menu.component.html',
    styleUrls: ['./model-menu.component.css']
})
export class ModelMenuComponent implements OnInit {
    @Output() clickImg=new EventEmitter();

    constructor(private http: HttpClient, private elementRef: ElementRef) {
        this.loadData();
      }

    dataList: any[]=[];
    currentPage = 1;
    pageSize = 50;
    currentModel: any;
    total: number;
    searchVal: string;

    setImageMode(model){
        this.currentModel=model;
        this.clickImg.emit(model);
        console.log(model);
    }

    isModeActive(id){
        return this.currentModel && this.currentModel.id===id;
    }

    loadData() {
        if((this.currentPage-1)*this.pageSize>this.total){
            return;
        }
        this.getData(this.currentPage, this.pageSize).then(data => {
          this.dataList = this.dataList.concat(data);
          this.currentPage++;
        });
    }

    getData(pageIndex: number, pageSize: number) {
        return new Promise((resolve,reject)=>{
            this.http.post('/entityApi/entityType/list/v2',{
                categoryCode: '',
                current: pageIndex,
                search: this.searchVal ? this.searchVal : undefined,
                size:pageSize,
                type: 'entity'
              }).subscribe((res: any)=>{
                if(res.code===200){
                    const records=res.data.records.map(r=>({
                        ...r,
                        deviceId:r.id,
                        defineType: 'model',
                        src:r.iconUrl?r.iconUrl:'assets/images/device.png'
                    }));
                    this.total=res.data.total;
                    resolve(records);
                }

              });
        });
    }

    clearActive(){
        this.currentModel=null;
    }

    onEnter(clear=false) {
        if(clear){
            this.searchVal='';
        }
        this.currentPage=1;
        this.total=0;
        this.dataList=[];
        this.loadData();
        // console.log('Enter key pressed with value:', this.searchVal);
    }

    onScroll=lodash.throttle(function(event) {
        const element = event.target;
        const atBottom = element.scrollHeight - element.scrollTop < element.clientHeight+20;
        if (atBottom) {
          this.loadData();
        }
    },500);


    ngOnInit() {
        console.log('初始化');
    }


}
